package com.d2.upload.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.http.HttpUtil;
import com.d2.upload.entity.AmazonFileModel;
import com.d2.upload.service.AmazonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@RequestMapping("ueditor")
@RestController
public class UeditorController {
    @Autowired
    private AmazonService amazonService;

    private MultipartFile downloadImage(String url){
        byte[] bytes = HttpUtil.downloadBytes(url);
        int i = FileUtil.lastIndexOfSeparator(url);
        String filename = url.substring(i + 1);

        String[] split = filename.split("\\.");
        String name = split[0];
        String ext = split[1];

        return new MultipartFile(){
            @Override
            public String getName() {
                return filename;
            }

            @Override
            public String getOriginalFilename() {
                return filename;
            }

            @Override
            public String getContentType() {
                return "image/"+ ext;
            }

            @Override
            public boolean isEmpty() {
                return bytes == null || bytes.length == 0;
            }

            @Override
            public long getSize() {
                return bytes.length;
            }

            @Override
            public byte[] getBytes() {
                return bytes;
            }

            @Override
            public InputStream getInputStream() throws IOException {
                return new ByteArrayInputStream(bytes);
            }

            @Override
            public void transferTo(File file) throws IllegalStateException {

            }
        };
    }

    @RequestMapping("")
    public Object ueditor(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        String action = request.getParameter("action");
        switch (action){
            case "config":
                InputStream inputStream = new ClassPathResource("ueditor.config.json").getInputStream();
                ServletOutputStream outputStream = response.getOutputStream();
                IoUtil.copy(inputStream, outputStream);
                return null;
            case "uploadimage":
            case "uploadvideo":
            case "uploadfile":
                AmazonFileModel upload = amazonService.upload(file);
                Map<String, Object> result = new HashMap<>();
                result.put("state", "SUCCESS");
                result.put("url", upload.getUrl());
                result.put("title", upload.getFileName());
                result.put("original", upload.getFileName());
                return result;
            case "uploadscrawl":
                String scrawlData = request.getParameter("scrawl");
                byte[] decode = Base64.decode(scrawlData);
                MultipartFile multipartFile = new MultipartFile(){
                    @Override
                    public String getName() {
                        return "scrawl_"+System.currentTimeMillis()+".png";
                    }

                    @Override
                    public String getOriginalFilename() {
                        return "scrawl.png";
                    }

                    @Override
                    public String getContentType() {
                        return "image/png";
                    }

                    @Override
                    public boolean isEmpty() {
                        return decode == null || decode.length == 0;
                    }

                    @Override
                    public long getSize() {
                        return decode.length;
                    }

                    @Override
                    public byte[] getBytes() {
                        return decode;
                    }

                    @Override
                    public InputStream getInputStream() throws IOException {
                        return new ByteArrayInputStream(decode);
                    }

                    @Override
                    public void transferTo(File file) throws IOException, IllegalStateException {

                    }
                };
                upload = amazonService.upload(multipartFile);
                result = new HashMap<>();
                result.put("state", "SUCCESS");
                result.put("url", upload.getUrl());
                result.put("title", upload.getFileName());
                result.put("original", upload.getFileName());
                return result;
            case "catchremoteimage":
                String[] images = request.getParameterValues("remoteimage[]");
                List<Map<String,Object>> resultList = new ArrayList<>();
                for (String image:images) {
                    try {
                        Map<String,Object> item = new HashMap<>();
                        MultipartFile multipartFile1 = downloadImage(image);
                        AmazonFileModel upload1 = amazonService.upload(multipartFile1);
                        item.put("source",image);
                        item.put("url",upload1.getUrl());
                        item.put("state","SUCCESS");
                        resultList.add(item);
                    }catch (Exception e){

                    }
                }
                result = new HashMap<>();
                result.put("state","SUCCESS");
                result.put("list", resultList);
                return result;
            default:
                return null;
        }
    }
}
